<?php

namespace backend\models;

use Yii;
use yii\base\Model;

/**
 * Description of UploadForm
 *
 * @author fireloong
 */
class UploadForm extends Model
{

    public $file;
    public $path = '@common/tmp/';
    public $exts = '';
    public $maxSize = 1024 * 1024 * 10;

    public function rules(): array
    {
        return [
            [['file'], 'file', 'skipOnEmpty' => false, 'extensions' => $this->exts, 'maxSize' => $this->maxSize]
        ];
    }

    /**
     * 上传文件
     * @param string $path 上传路径
     * @param bool $cover 是否允许覆盖
     * @return bool 上传成功返回 true；否则返回 false
     */
    public function upload($path = '', $cover = false)
    {
        if ($this->validate()) {
            $this->path = Yii::getAlias(rtrim($path ?: $this->path, '/') . '/');

            if (!is_dir($this->path)) {
                $this->addError('path', Yii::t('common', 'PATH_INVALID', $this->path));
                return false;
            }
            $filePath = $this->path . $this->file->baseName . '.' . $this->file->extension;
            if (is_file($filePath) && !$cover) {
                $this->addError('file', Yii::t('common', 'FILE_ALREADY_EXISTS'));
                return false;
            } else {
                $this->file->saveAs($filePath);
                return true;
            }
        } else {
            return false;
        }
    }

}
